﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.Services
{
    public class AppAuthorizationService
    {
        public ServiceResult<Entities.EAppAuthorization> Create(string userId, string name, string description)
        {
            using(EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EAppAuthorization> aaRep = new EntityRepository<Entities.EAppAuthorization>(dbContext);
                Entities.EAppAuthorization appAuth = aaRep.Get(p => p.AppName == name);
                if(appAuth != null)
                {
                    return new ServiceResult<Entities.EAppAuthorization>(false, ErrorCode.COM_OBJExist, ErrorCode.String(ErrorCode.COM_OBJExist));
                }
                    
                 appAuth =   new Entities.EAppAuthorization();
                appAuth.Id = Guid.NewGuid();
                appAuth.AppId = Guid.NewGuid();
                appAuth.AppName = name;
                appAuth.Description = description;
                appAuth.IsEnabled = true;
                appAuth.CreatedTime = DateTime.Now;
                appAuth.Creator = userId;
                appAuth.Token = DES.Hash_MD5_32(string.Format("{0}-{1}", appAuth.AppId, appAuth.AppName));//DES.EncryptString(string.Format("{0}-{1}", appAuth.AppId, appAuth.AppName), "cppeietl");

                aaRep.Create(appAuth);

                try
                {
                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult<Entities.EAppAuthorization>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), appAuth);
                    }
                    else
                    {
                        return new ServiceResult<Entities.EAppAuthorization>(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                    }
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("授权外部程序:{0}出错,ex:{1}", name,  ex));
                    return new ServiceResult<Entities.EAppAuthorization>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        public PagedList<Entities.EAppAuthorization> GetList(string filter, int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EAppAuthorization> aaRep = new EntityRepository<Entities.EAppAuthorization>(dbContext);

                if (string.IsNullOrEmpty(filter))
                {
                    List<Entities.EAppAuthorization> list = aaRep.Query().OrderBy(p => p.AppName).Take(limit).Skip(start).ToList();
                    int total = aaRep.Count();

                    return new PagedList<Entities.EAppAuthorization>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, list);
                }
                else
                {
                    List<Entities.EAppAuthorization> list = aaRep.Query(p=>p.AppName.Contains(filter)).OrderBy(p => p.AppName).Take(limit).Skip(start).ToList();
                    int total = aaRep.Count(p => p.AppName.Contains(filter));

                    return new PagedList<Entities.EAppAuthorization>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, list);
                }
            }
        }

        public ServiceResult<Entities.EAppAuthorization> Get(Guid appId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EAppAuthorization> aaRep = new EntityRepository<Entities.EAppAuthorization>(dbContext);

                Entities.EAppAuthorization eApp = aaRep.Get(p => p.AppId == appId);

                if(eApp == null)
                {
                    return new ServiceResult<Entities.EAppAuthorization>(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }

                return new ServiceResult<Entities.EAppAuthorization>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), eApp);
            }
        }


        public ServiceResult Delete(Guid id)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EAppAuthorization> aaRep = new EntityRepository<Entities.EAppAuthorization>(dbContext);
                Entities.EAppAuthorization eAppAuth = aaRep.Get(p => p.Id == id);
                if (eAppAuth != null)
                {
                    aaRep.Delete(eAppAuth);
                    try
                    {
                        if (dbContext.SaveChanges() > 0)
                        {
                            return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                        }
                        else
                        {
                            return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("删除外部程序授权:{0}出错,ex:{1}", id, ex));
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                else
                {
                    return new ServiceResult(true, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }


        public ServiceResult Enable(Guid id)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EAppAuthorization> aaRep = new EntityRepository<Entities.EAppAuthorization>(dbContext);
                Entities.EAppAuthorization eAppAuth = aaRep.Get(p => p.Id == id);
                if (eAppAuth != null)
                {
                    if(eAppAuth.IsEnabled == true)
                    {
                        return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                    }
                    eAppAuth.IsEnabled = true;
                    aaRep.Update(eAppAuth);
                    try
                    {
                        if (dbContext.SaveChanges() > 0)
                        {
                            return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                        }
                        else
                        {
                            return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("启用外部程序授权:{0}出错,ex:{1}", id, ex));
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }

        public ServiceResult Disable(Guid id)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EAppAuthorization> aaRep = new EntityRepository<Entities.EAppAuthorization>(dbContext);
                Entities.EAppAuthorization eAppAuth = aaRep.Get(p => p.Id == id);
                if (eAppAuth != null)
                {
                    if (eAppAuth.IsEnabled == false)
                    {
                        return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                    }
                    eAppAuth.IsEnabled = false;
                    aaRep.Update(eAppAuth);
                    try
                    {
                        if (dbContext.SaveChanges() > 0)
                        {
                            return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                        }
                        else
                        {
                            return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("禁用外部程序授权:{0}出错,ex:{1}", id, ex));
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }
    }

    class DES
    {
        public static string Hash_MD5_32(string word, bool toUpper = true)
        {
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP
                    = new System.Security.Cryptography.MD5CryptoServiceProvider();

                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
                byte[] bytHash = MD5CSP.ComputeHash(bytValue);
                MD5CSP.Clear();

                //根据计算得到的Hash码翻译为MD5码
                string sHash = "", sTemp = "";
                for (int counter = 0; counter < bytHash.Count(); counter++)
                {
                    long i = bytHash[counter] / 16;
                    if (i > 9)
                    {
                        sTemp = ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp = ((char)(i + 0x30)).ToString();
                    }
                    i = bytHash[counter] % 16;
                    if (i > 9)
                    {
                        sTemp += ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp += ((char)(i + 0x30)).ToString();
                    }
                    sHash += sTemp;
                }

                //根据大小写规则决定返回的字符串
                return toUpper ? sHash : sHash.ToLower();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        // 创建Key
        public string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }
        // 加密字符串
        public static string EncryptString(string sInputString, string sKey)
        {
            byte[] data = Encoding.UTF8.GetBytes(sInputString);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            //string s1 = BitConverter.ToString(result);

            //string s3 = s1.Replace("-", string.Empty);
            string s2 = toBitString(result);

            return s2;
        }

        // 解密字符串
        public static string DecryptString(string sInputString, string sKey)
        {
            //string[] sInput = sInputString.Split('-');
            //byte[] data = new byte[sInput.Length];
            //for (int i = 0; i < sInput.Length; i++)
            //{
            //    data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
            //}

            byte[] data = new byte[sInputString.Length / 2];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = byte.Parse(sInputString.Substring(i * 2, 2), NumberStyles.HexNumber);
            }
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateDecryptor();
            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return Encoding.UTF8.GetString(result);
        }

        internal static string toBitString(byte[] data)
        {
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < data.Length; index++)
            {
                builder.AppendFormat("{0:X2}", data[index]);
            }
            return builder.ToString();
        }
    }
}
